﻿using System;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Navigation;
using System.Windows.Threading;
using CeskyRozhlasWP8.Model;
using CeskyRozhlasWP8.Resources;
using CeskyRozhlasWP8.ViewModel;
using Microsoft.Phone.BackgroundAudio;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;

namespace CeskyRozhlasWP8.View
{
    public partial class RadiostationPage : PhoneApplicationPage
    {
        private DispatcherTimer _progressBarRefreshTimer;
        private readonly RadioStationPageViewModel _radioStationPageVm = new RadioStationPageViewModel();

        public RadiostationPage()
        {
            InitializeComponent();
            DataContext = _radioStationPageVm;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[0]).Text = AppResources.SettingsMenuItemText;
            ((ApplicationBarIconButton)ApplicationBar.Buttons[1]).Text = AppResources.PlayMenuItemText;

        }

        private void progressBarRefreshTimer_Tick(object sender, EventArgs e)
        {
            UpdateProgressBar();
        }

        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            BackgroundAudioPlayer.Instance.PlayStateChanged += BackgroundPlaybackStateChanged;

            StartProgressbarRefreshTimer();
            UpdatePlaybackControls();
            await UpdateStationDetails();
            UpdateProgressBar();
        }

        private void StartProgressbarRefreshTimer()
        {
            _progressBarRefreshTimer = new DispatcherTimer {Interval = TimeSpan.FromSeconds(1)};
            _progressBarRefreshTimer.Tick += progressBarRefreshTimer_Tick;
            _progressBarRefreshTimer.Start();
        }

        private async Task UpdateStationDetails()
        {
            String strId = NavigationContext.QueryString["stationid"];
            _iStationId = 0;
            Int32.TryParse(strId, out _iStationId);
            await _radioStationPageVm.RefetchStationDetails(_iStationId);
            await _myStreamSelector.ReinitAsync(_iStationId);
            String autoPlay = NavigationContext.QueryString["autoPlay"];
            if (autoPlay != null && autoPlay == "true")
            {
                //Add a check if there is something scheduled for now.
                Play();
            }
        }


        private void UpdatePlaybackControls()
        {
            SyncWithPlayerPlayingState();
        }

        private void UpdateProgressBar()
        {
            if (_radioStationPageVm.CurrentSchedule != null && _radioStationPageVm.CurrentSchedule.Count > 0)
            {
                var aLocalStartTime = _radioStationPageVm.CurrentSchedule[0].StartTime.ToLocalTime();
                var aLocalStopTime = _radioStationPageVm.CurrentSchedule[0].StopTime.ToLocalTime();
                MyProgressBar.Minimum = 0;
                var aDuration = aLocalStopTime.Subtract(aLocalStartTime);
                var aCurrentStatus = DateTime.Now.Subtract(aLocalStartTime);
                MyProgressBar.Maximum = aDuration.TotalMilliseconds;
                MyProgressBar.Value = aCurrentStatus.TotalMilliseconds;
                MyProgressBar.Visibility = Visibility.Visible;
            }
        }

        

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            StopProgressBarRefreshTimer();
            BackgroundAudioPlayer.Instance.PlayStateChanged -= BackgroundPlaybackStateChanged;
            base.OnNavigatedFrom(e);
        }

        private void StopProgressBarRefreshTimer()
        {
            if (_progressBarRefreshTimer != null)
            {
                //TODO: where is Dispose method for this timer? Should I manually do "-="?
                _progressBarRefreshTimer.Tick -= progressBarRefreshTimer_Tick;
                _progressBarRefreshTimer.Stop();
                _progressBarRefreshTimer = null;
            }
        }


        private readonly MobileServiceStreamSelector _myStreamSelector = new MobileServiceStreamSelector();
        private int _iStationId;
        private string _buttonText;

        private void playButton_Click(object sender, RoutedEventArgs e)
        {
            Play();
        }

        private void Play()
        {
            AudioTrack aTrack = _myStreamSelector.GetStream(_iStationId);
            if (aTrack != null)
            {
                BackgroundAudioPlayer.Instance.Track = aTrack;
                BackgroundAudioPlayer.Instance.Play();

                //TODO: maybe expose some error when aTrack is null?
            }
        }

        private void BackgroundPlaybackStateChanged(object sender, EventArgs e)
        {
            SyncWithPlayerPlayingState();
        }

        private void SyncWithPlayerPlayingState()
        {
            bool isStopped = BackgroundAudioPlayer.Instance.PlayerState == PlayState.Paused ||
                BackgroundAudioPlayer.Instance.PlayerState == PlayState.Stopped ||
                BackgroundAudioPlayer.Instance.PlayerState == PlayState.Unknown;
            UpdateStartStopVisibility(isStopped);
        }

        private void UpdateStartStopVisibility(bool isStopped)
        {
            _buttonText = isStopped ? AppResources.PlayMenuItemText : AppResources.StopMenuItemText;

            if (ApplicationBar.Buttons[1] is ApplicationBarIconButton &&
                (ApplicationBar.Buttons[1] as ApplicationBarIconButton).Text == _buttonText)
            {
                //Nothing to do
                return;
            }
            var aDesiredButonUri = isStopped ? "/Images/transport.play.png" : "/Images/transport.pause.png";
            var appBarButton = new ApplicationBarIconButton(new Uri(aDesiredButonUri, UriKind.Relative))
            {
                Text = _buttonText
            };
            if (isStopped)
            {
                appBarButton.Click += PrehratMenuItemClick;
            }
            else
            {
                appBarButton.Click += ZastavitMenuItemClick;
            }

            ApplicationBar.Buttons.RemoveAt(1);
            ApplicationBar.Buttons.Insert(1, appBarButton);

        }


        private void stopButton_Click(object sender, RoutedEventArgs e)
        {
            Stop();
        }

        private static void Stop()
        {
            BackgroundAudioPlayer.Instance.Stop();
        }

        private void PrehratMenuItemClick(object sender, EventArgs e)
        {
            Play();
        }
        private void ZastavitMenuItemClick(object sender, EventArgs e)
        {
            Stop();
        }

        private void NastaveniMenuItemClick(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }



        private void ShowSelected(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var aUiElement = sender as FrameworkElement;
            if (aUiElement != null)
            {
                var aShow = aUiElement.DataContext as DetailedScheduleItem;
                if (aShow != null)
                {
                    NavigationService.Navigate(new Uri("/FullShowDescriptionPage.xaml?showId=" + aShow.Id, UriKind.Relative));
                }
            }
        }

    }
}
